import { app, protocol, BrowserWindow, ipcMain } from 'electron';
import path from 'path';
import { fileURLToPath } from 'url';
import grpcClient from './grpcClient.js';
import fs from 'fs';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const isDevelopment = !app.isPackaged;
console.log('App is packaged:', app.isPackaged);
console.log('isDevelopment:', isDevelopment);

const createVST3Parameter = (labelName, parameterId, processorId) => ({
    labelName,
    parameterId,
    processorId
});

const PluginType = {
  DUMMY: 0,
  INTERNAL: 1,
  VST2X: 2,
  VST3X: 3,
  LV2: 4
};

const AmplifierNo = {
    Eddie51Amplifier: 1,
    DizzlVHAmplifier: 2,
    SoloistAmplifier: 3
}

const amplifierConfigs = {
    SoloistAmplifier: {
        name: "Soloist Amplifier",
        uid: "com.example.SoloistAmplifier",
        path: "/path/to/SoloistAmplifier.vst3",
        type: 3,
        AmplifierNo: 1
    },
    Eddie51Amplifier: {
        name: "Eddie 51 Amplifier",
        uid: "com.example.Eddie51Amplifier",
        path: "/path/to/Eddie51Amplifier.vst3",
        type: 3,
        AmplifierNo: 0.1
    },
    DizzlVHAmplifier: {
        name: "Dizzl VH Amplifier",
        uid: "com.example.DizzlVHAmplifier",
        path: "/path/to/DizzlVHAmplifier.vst3",
        type: 3,
        AmplifierNo: 0.5
    }
};

const createVST3ParameterBank = () => {
    const parameterMap = new Map();

    return {
        addParameter: (labelName, parameterId, processorId) => {
            parameterMap.set(labelName, createVST3Parameter(labelName, parameterId, processorId));
        },
        getParameter: (labelName) => parameterMap.get(labelName),
        removeParameter: (labelName) => parameterMap.delete(labelName),
        getAllParameters: () => Array.from(parameterMap.values()),
        hasParameter: (labelName) => parameterMap.has(labelName),
        getParameterCount: () => parameterMap.size,
        updateProcessorId: (labelName, newProcessorId) => {
            const param = parameterMap.get(labelName);
            if (param) {
                param.processorId = newProcessorId;
                parameterMap.set(labelName, param);
            }
        }
    };
};

const parameterBanks = {
    SoloistAmplifier: createVST3ParameterBank(),
    Eddie51Amplifier: createVST3ParameterBank(),
    DizzlVHAmplifier: createVST3ParameterBank(),
    ParaPanel: createVST3ParameterBank()
};

protocol.registerSchemesAsPrivileged([
    { scheme: 'app', privileges: { secure: true, standard: true } }
]);

let isGrpcConnected = false;
let currentAmplifier = 'Eddie51Amplifier';
let currentProcessorId = null;
let paraPanelProcessorId = 1;
const AmpNumId = 1964973890;


async function createWindow() {
    const win = new BrowserWindow({
        width: 1920,
        height: 1080,
        resizable: false,
        // frame: false,
        // titleBarStyle: 'hidden',
        webPreferences: {
            nodeIntegration: false,
            contextIsolation: true,
            preload: path.join(__dirname, '../src/preload.js'),
            webviewTag: true,
            webSecurity: false,
            allowRunningInsecureContent: true
        }
    });

    if (isDevelopment) {
        console.log('Running in development mode');
        win.loadURL('http://localhost:5173');
      } else {
        console.log('Running in production mode');
        
        // 获取应用程序的根路径
        const appPath = app.getAppPath();
        console.log('App path:', appPath);
    
        // 构建 index.html 的路径
        const indexPath = path.join(appPath, 'dist', 'index.html');
        console.log('Attempting to load index from:', indexPath);
    
        // 检查文件是否存在
        if (fs.existsSync(indexPath)) {
          win.loadFile(indexPath).then(() => {
            console.log('Successfully loaded index.html');
          }).catch(err => {
            console.error('Failed to load index file:', err);
          });
        } else {
          console.error('index.html not found at:', indexPath);
          // 如果找不到文件，可以尝试加载一个错误页面或显示一个错误消息
          win.loadURL(`data:text/html;charset=utf-8,<h1>Error: Could not find index.html</h1><p>Path: ${indexPath}</p>`);
        }
      }

    try {
    const protoPath = app.isPackaged
        ? path.join(process.resourcesPath, 'protos', 'sushi_rpc.proto')
        : path.join(__dirname, '..', 'src', 'protos', 'sushi_rpc.proto');
    
    await grpcClient.connect('localhost:51051', protoPath);
    console.log('gRPC client connected successfully');
    } catch (error) {
    console.error('Failed to connect gRPC client:', error);
    }

    const hideScrollbarsCSS = 'html, body { overflow: hidden; }';
    win.webContents.on('did-finish-load', () => {
        win.webContents.insertCSS(hideScrollbarsCSS);
        win.webContents.send('enable-drag-navigation');
    });

    win.webContents.on('will-navigate', (event, url) => {
        // 如果需要，你可以在这里添加额外的导航控制
        console.log('Will navigate to:', url);
        win.webContents.insertCSS(hideScrollbarsCSS);
    });

    win.webContents.on('new-window', (event, url) => {
        // 阻止新窗口的打开，改为在当前窗口加载 URL
        event.preventDefault();
        win.loadURL(url);
    });

    win.webContents.on('did-finish-load', () => {
        win.webContents.insertCSS(hideScrollbarsCSS);
        win.webContents.send('enable-drag-navigation');
    });

    // const amplifierTypes = ['SoloistAmplifier', 'Eddie51Amplifier', 'DizzlVHAmplifier'];
    ipcMain.handle('switch-amplifier', async (event, amplifierType) => {
        if (!grpcClient.isConnected) {
            console.error('gRPC client is not connected. Cannot switch amplifier.');
            return { success: false, error: 'gRPC client not connected' };
        }

        if (!amplifierConfigs[amplifierType]) {
            console.error(`Invalid amplifier type: ${amplifierType}`);
            return { success: false, error: 'Invalid amplifier type' };
        }

        try {
            // await grpcClient.deleteProcessorFromTrack(2, 0);
            
            // // 这里需要添加创建新放大器的逻辑
            // const response = await grpcClient.createProcessorOnTrack('Overtone', 'Overtone', '/home/orangepi/.vst3/Overtone.vst3', PluginType.VST3X, 0, { addToBack: true });

            // await grpcClient.moveProcessorOnTrack(3,0,0,{ addToBack: true, beforeProcessor: 1 });
              
            // currentProcessorId = await grpcClient.getProcessorId('Overtone');
            console.log('amplifierConfig:', amplifierConfigs[amplifierType]);

            try {
                await grpcClient.setParameterValue(2, AmpNumId, amplifierConfigs[amplifierType].AmplifierNo);
                console.log('Amplifier type sent successfully:', 2, AmpNumId, amplifierConfigs[amplifierType].AmplifierNo);
            } catch (error) {
                console.error('Error changing amplifier type:', error);
            }

            currentAmplifier = amplifierType;          
            console.log(`Current amplifier: ${currentAmplifier}`);

            return { success: true, processorId: currentProcessorId };
        } catch (error) {
            console.error('Error switching amplifier:', error);
            return { success: false, error: error.message };
        }
    });

    ipcMain.on('send-knob-value', async (event, { knob, value }) => {  
        if (!grpcClient.isConnected) {
            console.error('gRPC client is not connected. Cannot send knob value.');
            return;
        }

        let targetParameterBank;

        if (parameterBanks.ParaPanel.hasParameter(knob)) {
            targetParameterBank = parameterBanks.ParaPanel;
        } else if (parameterBanks[currentAmplifier].hasParameter(knob)) {
            targetParameterBank = parameterBanks[currentAmplifier];
        } else {
            console.error('Invalid knob:', knob);
            return;
        }
        
        const knobPara = targetParameterBank.getParameter(knob);
        // console.log('knobPara:', knobPara);
        
        try {
            await grpcClient.setParameterValue(knobPara.processorId, knobPara.parameterId, value);
            // console.log('Knob value sent successfully:', knobPara.processorId, knobPara.parameterId, value);
        } catch (error) {
            console.error('Error sending knob value:', error);
        }
    });

    ipcMain.on('set-processor-bypass', async (event, { processorId, bypassState }) => {
        if (!grpcClient.isConnected) {
            console.error('gRPC client is not connected. Cannot set processor bypass state.');
            return;
        }

        try {
            await grpcClient.setProcessorBypassState(processorId, bypassState);
            console.log(`Processor ${processorId} bypass state set to ${bypassState}`);
        } catch (error) {
            console.error('Error setting processor bypass state:', error);
        }
    });
}

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit();
    }
});

app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
});

app.whenReady().then(() => {
    createWindow().catch(err => {
        console.error('Failed to create window:', err);
    });

    parameterBanks.ParaPanel.addParameter("INPUT", 0, 0);
    parameterBanks.ParaPanel.addParameter("THRESHOLD", 1, 1);
    parameterBanks.ParaPanel.addParameter("TIME", 1, 6);
    parameterBanks.ParaPanel.addParameter("FEEDBACK", 4, 6);
    parameterBanks.ParaPanel.addParameter("MIX", 2, 6);
    parameterBanks.ParaPanel.addParameter("REVERB MIX", 2, 7);
    parameterBanks.ParaPanel.addParameter("OUTPUT", 0, 0);

    parameterBanks.SoloistAmplifier.addParameter("PREAMP", 1805469906, 2);
    parameterBanks.SoloistAmplifier.addParameter("BASS", 2612626, 2);
    parameterBanks.SoloistAmplifier.addParameter("MIDDLE", 2612626, 2);
    parameterBanks.SoloistAmplifier.addParameter("TREBLE", 2612626, 2);
    parameterBanks.SoloistAmplifier.addParameter("PRESENCE", 2612626, 2);
    parameterBanks.SoloistAmplifier.addParameter("MASTER", 67801841, 2);

    parameterBanks.Eddie51Amplifier.addParameter("PRE GAIN", 1805469906, 2);
    parameterBanks.Eddie51Amplifier.addParameter("LOW", 2063103, 2);
    parameterBanks.Eddie51Amplifier.addParameter("MID", 157009333, 2);
    parameterBanks.Eddie51Amplifier.addParameter("HIGH", 365752948, 2);
    parameterBanks.Eddie51Amplifier.addParameter("PRESENCE", 935461147, 2);
    parameterBanks.Eddie51Amplifier.addParameter("POSTGAIN", 67801841, 2);

    parameterBanks.DizzlVHAmplifier.addParameter("GAIN", 1805469906, 2);
    parameterBanks.DizzlVHAmplifier.addParameter("BASS", 2063103, 2);
    parameterBanks.DizzlVHAmplifier.addParameter("MIDDLE", 157009333, 2);
    parameterBanks.DizzlVHAmplifier.addParameter("TREBLE", 365752948, 2);
    parameterBanks.DizzlVHAmplifier.addParameter("PRESENCE", 935461147, 2);
    parameterBanks.DizzlVHAmplifier.addParameter("VOLUME", 67801841, 2);
});

if (isDevelopment) {
    process.on('SIGTERM', () => {
        app.quit();
    });
}